package com.tyjc.unique.ssq;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.tyjc.unique.net.StringResultBean;
import com.tyjc.unique.net.StringResultBean_New;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.App;
import com.fyzk.activity.lottery.shuzicai.BallInfo;
import com.fyzk.activity.zhifu.NumLotteryZhiFuActivity;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.betcode.BetLotteryInfo;
import com.fyzk.betcode.CodeFactory;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.umeng.analytics.MobclickAgent;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

import http.DataUtil.text.TextUtil;
import http.XRequestCallBack;


/**
 * 所有Fragment的基类
 */
public class BaseFragment extends Fragment implements OnClickListener {

    protected final String TAG = this.getClass().getSimpleName();

    protected BaseActivity mActivity;
    protected App mApp;
    protected Intent intent;

//    @Override
//    public void onCreateView(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        mActivity = (BaseActivity) getActivity();
//        mApp = (App) mActivity.getApplication();
//    }


    /**
     * 初始化 小球list
     *
     * @param balls
     * @param count 每列显示小球数
     * @param start
     */
    public void initBallList(List<BallInfo> balls, int count, int start,
                             boolean hasZero) {
        balls.clear();
        for (int j = start; j < count + start; j++) {
            BallInfo qiu;
            if (hasZero) {
                if (j < 10) {
                    qiu = new BallInfo("0" + j);
                } else {
                    qiu = new BallInfo("" + j);
                }
            } else {
                qiu = new BallInfo(String.valueOf(j));
            }
            balls.add(qiu);
        }
    }

    public void ssqBet(List<List<BallInfo>> arrs,int zhushu ) {
        int wcodeId = LotteryIDUtils.SSQ_LOTTERY_COMMON_DAN_ID_INT;
        if (zhushu > 1) {
            wcodeId = LotteryIDUtils.SSQ_LOTTERY_COMMON_FU_ID_INT;
        } else {
            wcodeId = LotteryIDUtils.SSQ_LOTTERY_COMMON_DAN_ID_INT;
        }
        ssqTouZhu1(arrs,wcodeId, zhushu);
    }
    public void dltBet(List<List<BallInfo>> arrs,int zhushu ) {
        int wcodeId = LotteryIDUtils.DLT_LOTTERY_COMMON_DAN_ID_INT;
        if (zhushu > 1) {
            wcodeId = LotteryIDUtils.DLT_LOTTERY_COMMON_FU_ID_INT;
        } else {
            wcodeId = LotteryIDUtils.DLT_LOTTERY_COMMON_DAN_ID_INT;
        }
        dltTouZhu1(arrs,wcodeId, zhushu);
    }

    public void ssqTouZhu1(List<List<BallInfo>> arrs, int wcodeId, long zhuShu) {
        StringBuffer strB = new StringBuffer();
        for (int i = 0; i < arrs.size(); i++) {
            List<BallInfo> infos = arrs.get(i);
            for (int j = 0; j < infos.size(); j++) {
                BallInfo info = infos.get(j);
                if (info.isSelected()) {
                    strB.append(info.getNum());
                    strB.append(",");
                }
            }
            if (strB.length() > 0) {//去除多余的“,”
                strB.deleteCharAt(strB.length() - 1);
            }
            strB.append("|");
        }

        if (strB.length() > 0) {//去除多余的“|”
            strB.deleteCharAt(strB.length() - 1);
        }
        String Zhuma = strB.toString();
        String showZhuMa =  CodeFactory.getCode(LotteryIDUtils.SSQ_LOTTERY_ID_INT).formatHtmlCode2(Zhuma);
        AppLotteryCodeListManager.getInstance().AddLotteryInfo(wcodeId, Zhuma,
                showZhuMa, zhuShu, arrs, 0);
        BetLotteryInfo betInfo = new BetLotteryInfo(wcodeId, Zhuma, showZhuMa,
                zhuShu, arrs, 0);
        Intent intent = new Intent(getContext(), NumLotteryZhiFuActivity.class);
        intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.SSQ_LOTTERY_ID_INT);
        intent.putExtra("bet", (Serializable) betInfo);
        startActivity(intent);
    }
    public void dltTouZhu1(List<List<BallInfo>> arrs, int wcodeId, long zhuShu) {
        StringBuffer strB = new StringBuffer();
        for (int i = 0; i < arrs.size(); i++) {
            List<BallInfo> infos = arrs.get(i);
            for (int j = 0; j < infos.size(); j++) {
                BallInfo info = infos.get(j);
                if (info.isSelected()) {
                    strB.append(info.getNum());
                    strB.append(",");
                }
            }
            if (strB.length() > 0) {//去除多余的“,”
                strB.deleteCharAt(strB.length() - 1);
            }
            strB.append("|");
        }

        if (strB.length() > 0) {//去除多余的“|”
            strB.deleteCharAt(strB.length() - 1);
        }
        String Zhuma = strB.toString();
        String showZhuMa =   CodeFactory.getCode(LotteryIDUtils.DLT_LOTTERY_ID_INT).formatHtmlCode2(Zhuma);;
        AppLotteryCodeListManager.getInstance().AddLotteryInfo(wcodeId, Zhuma,
                showZhuMa, zhuShu, arrs, 0);
        BetLotteryInfo betInfo = new BetLotteryInfo(wcodeId, Zhuma, showZhuMa,
                zhuShu, arrs, 0);
        Intent intent = new Intent(getContext(), NumLotteryZhiFuActivity.class);
        intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.DLT_LOTTERY_ID_INT);
        intent.putExtra("bet", (Serializable) betInfo);
        startActivity(intent);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {
        mActivity = (BaseActivity) getActivity();
        mApp = (App) mActivity.getApplication();
        return x.view().inject(this, inflater, container);//xutil注解;;
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
    }


    public void showData() {
    }

    public void back() {

    }


    public void sendRequest(HttpMethod method, RequestParams params, int requestCode) {
        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                onFailure(getRequestCode(), "9999", "网络异常");
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                LogUtil.d("联网：解密后返回>" + result.toString());

                try {
                    StringResultBean_New resultBean = JSON.parseObject(result,
                            StringResultBean_New.class);
                    if ((resultBean.getErrorcode()!=null&&resultBean.getErrorcode().equals("0"))||(resultBean.getErrorCode()!=null&&resultBean.getErrorCode().equals("0"))) {
                        BaseFragment.this.onSuccess(getRequestCode(), resultBean,
                                result);
                    } else {
                        if(!TextUtil.isEmpty(resultBean.getErrorcode())){

                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        }else{
                            onFailure(getRequestCode(), resultBean.getErrorCode(), resultBean.getMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(getRequestCode(), "9999",
                            result);
                }

            }
        };


        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }

    }

    protected void onFailure(int requestCode, String errorcode, String msg) {
        cancelProgressDialog();
    }

    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String result) {
        cancelProgressDialog();
    }


    public Context getContext() {
        return mActivity;
    }


    /**
     * 取消提示dialog显示
     */
    public void cancelProgressDialog() {
//        if (progressDg != null && progressDg.isShowing()) {
//            progressDg.cancel();
//        }
    }

    /**
     * 显示提示
     */
    public void showProgressDialog() {
//        if(!getContext().isFinishing()){
//            if (progressDg == null || !progressDg.isShowing()) {
//                progressDg = CustomProgress.show(getContext(), null, false, null);
//            }
//        }
    }

    /**
     * 提示
     *
     * @param text
     */
    public void showToast(String text) {
        Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int resId) {
        Toast.makeText(getActivity(), resId, Toast.LENGTH_SHORT).show();
    }

    /**
     * 点击事件处理
     */
    @Override
    public void onClick(View v) {
        if (isHidden()) {
            return;
        }
    }

    /**
     * 启动Activity
     *
     * @param cls void
     */
    public void startActivity(Class<? extends Activity> cls) {
        Intent intent = new Intent(getActivity(), cls);
        startActivity(intent);
//		@SuppressWarnings("deprecation")
//		int version = Integer.valueOf(android.os.Build.VERSION.SDK);
//		if (version >= 5) {
//			getActivity().overridePendingTransition(0, 0);
//		}
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


    protected void onFailure(int requestCode) {
        showToast("网络异常");
    }

    ;

    protected void onFailure(int requestCode, StringResultBean resultBean) {
        showToast(resultBean.getMsg());

    }

    /**
     * 刷新数据
     */
    public void refreshData() {

    }

}
